from django.contrib.auth.hashers import make_password
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import serializers

from apps.UserManagement.models import User, WrongQuestions
from ..PaperManagement.models import PaperQuestion


class UserSerializer(serializers.ModelSerializer):
    depart = serializers.CharField(source='depart.name', read_only=True)

    class Meta:
        model = User
        fields = "__all__"
        extra_kwargs = {
            'password': {'write_only': True}  # 密码字段只写
        }

    def create(self, validated_data):
        # 在创建用户时，将密码加密
        password = validated_data.pop('password')
        user = User.objects.create(**validated_data)
        user.password = make_password(password)
        user.save()
        return user


class ApiLoginSerializer(serializers.ModelSerializer):
    """接口文档登录-序列化器"""

    username = serializers.CharField()
    password = serializers.CharField()

    class Meta:
        model = User
        fields = ["username", "password"]


class UserListSerializer(serializers.ModelSerializer):
    """用户列表序列化"""
    depart = serializers.CharField(source='depart.name', read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'name', 'user_type', 'status', 'phone', 'email', 'depart', 'create_time',
                  'update_time']


from .models import File


class FileSerializer(serializers.ModelSerializer):
    class Meta:
        model = File
        fields = ['id', 'file', 'uploaded_at']


class WrongQuestionSerializer(serializers.ModelSerializer):
    user = serializers.CharField(source='user.name', read_only=True)
    questionsInfo = serializers.SerializerMethodField()

    class Meta:
        model = WrongQuestions
        fields = '__all__'

    def get_questionsInfo(self, obj):
        question = obj.question

        # 返回试题信息
        question_info = {
            "id": str(question.id),
            "topic": question.topic,
            "type": question.type,
            "classify": question.classify,
            "difficulty": question.difficulty,
        }

        # 根据题目类型返回答案或关键词
        if question.type == "short":
            question_info["keywords"] = question.keywords
        else:
            question_info["options"] = question.options
            question_info["answer"] = question.answer

        return question_info
